package com.swim.session;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.jboss.ejb3.annotation.LocalBinding;
import org.jboss.ejb3.annotation.RemoteBinding;
import com.swim.entity.Skill;

@Stateless
@RemoteBinding(jndiBinding="SkillBeanJNDI")
@LocalBinding(jndiBinding = "SkillBeanLocalJNDI")
public class SkillBean implements SkillLocal, SkillRemote {

	@PersistenceContext(unitName = "SWIM")
	EntityManager database;
	
	/**
	 * @param name the name of the skill
	 * @param description the description of the skill
	 */
	public void newSkill(String name, String description) {
		Skill s = new Skill(name, description);
		database.persist(s);
	}
	
	/**
	 * @return the list of skill's name
	 */
	public List<String> getSkillNames() {
		List<String> names = new ArrayList<String>();
		for (Skill s : getSkills()) {
			names.add(s.getName());
		}
		return names;
	}

	/**
	 * @return the list of skill
	 */
	public List<Skill> getSkills() {
		List<Skill> skills = new ArrayList<Skill>();
		try {
    		Query q = database.createQuery("SELECT s FROM Skill s");
    		List<Skill> results =  (List<Skill>) q.getResultList();
    		skills.addAll(results);
    		
    	} catch (EntityNotFoundException exc) { 
    		System.err.println("UFF6");
    	} catch (NonUniqueResultException exc) {
    		System.err.println("UFF7");
    	}
    	return skills;
	}
	
	/**
	 * @param name the name of the skill
	 * @return the list of skill selected by name
	 */
	public Skill getSkillByName(String name) {
		try {
    		Query q = database.createQuery("SELECT s FROM Skill s WHERE s.name=:name");
    		q.setParameter("name", name);
    		Skill result = (Skill)q.getSingleResult();
    		return result;
    		
    	} catch (EntityNotFoundException exc) { 
    		System.err.println("UFF6");
    	} catch (NonUniqueResultException exc) {
    		System.err.println("UFF7");
    	}
		return null;
	}

	/**
	 * @param email the email of the user
	 * @return the user's skill
	 */
	public List<Skill> getSkillByEmail(String email) {
		try {
    		Query q = database.createQuery("SELECT s FROM RegisteredUser as r, IN (r.userSkills) s WHERE r.email = :email");
    		q.setParameter("email", email);
    		List<Skill> result = (List<Skill>) q.getResultList();
    		return result;
    		
    	} catch (EntityNotFoundException exc) { 
    		System.err.println("UFF6");
    	} catch (NonUniqueResultException exc) {
    		System.err.println("UFF7");
    	}
		return null;
	}
}
